<template>
  <div class="detail">
<header-bar :text="title" :left="left" :right="right" @rightClick="rightClick"></header-bar>
<div class="det_head">
<div class="det_head_fir">
  <p>{{list.type==1?"固定年化收益率":list.type==2?"预计年化收益率":"固定年化收益率"}}</p>
  <span>{{list.profit}}%</span>
  
</div>
<div class="det_head_sec">
  <p>锁定期</p>
  <span>{{list.dayType}}天</span>
</div>
</div>
<div class="det_bq">
  <span>钱包存管</span>
  <span>资产保值系统</span>
  <span>安全等级A</span>
</div>
<div class="det_num">
    <div class="det_num_h">
      <span class="det_num_l">{{list.coinType}}锁仓数量&nbsp;&nbsp;{{cote}}</span>
      <span><span class="det-time">{{time}}</span> 后截止募集</span>
    </div>
    <div class="det_count">
      <mt-progress :value="lineVal" :bar-height="10"></mt-progress>
    </div>
</div>
<div class="det_num_list">
  <ul>
    <li>
      <span>抢购总额度</span>
      <span>{{list.totalAmountView}}</span>
    </li>
    <li>
      <span>剩余额度</span>
      <span>{{list.surplusAmountView}}</span>
    </li>
    <li>
      <span>最低起购数量</span>
      <span>{{list.quantity}}</span>
    </li>
  </ul>
</div>
 <div class="history" style="color:#888;">
    <mt-cell title="往期产品收益" is-link @click.native="goHis"></mt-cell>
 </div>
	<div style="padding-bottom:49px;">
	<div>
	<Card title="保证币量特点" >
		<div class="b-te">
			<div class="b-te-item">
				<img src="../assets/info3.png" alt="">
				<p>量化自动套利</p>
			</div>
			<div class="b-te-item">
				<img src="../assets/info1.png" alt="">
				<p>低风险</p>
			</div>
			<div class="b-te-item">
				<img src="../assets/info2.png" alt="">
				<p>收益稳定</p>
			</div>
		</div>
	</Card>
	<Card title="保证币量详情" >
     <!-- v-html="list.detail || '国内知名量化团队提供风险量化交易规则，安全稳定量 化结果。国内知名量化团队提供风险量化交易规则，安 全稳定量化结果'" -->
		<div class="binfo">{{list.detail}}</div>
	</Card>
	<Card title="常见问题" >
		<div class="det_pro_qa">
			<p><span>Q</span>什么是币金所？</p>
			<p><span>A</span>币金所是基于数字资产的理财产品，每一个项目有相应的锁定周期和利率，您可以自由选择购买，若是选择固收类产品，购买后本金锁定，根据约定时间开始计算收益，产品到期后本金和收益会自动转入账户，您可以选择续投或者提现。</p>
		</div>
		<div class="det_pro_qa" v-if="open">
			<p><span>Q</span>收益如何计算？</p>
			<p><span>A</span>参与币金所的产品均有固定的开始和结束时间，在此周期内计算您可获取的收益。每个产品的收益和周期可以在产品页面查询到。</p>
		</div>
		<div class="det_pro_qa" v-if="open">
			<p><span>Q</span>收益如何发放？</p>
			<p><span>A</span>产品锁定期到期后，系统会开始陆续发放到购买了的用户的账户，您可以在个人首页查阅。</p>
		</div>
		<div class="det_pro_qa" v-if="open">
			<p><span>Q</span>参与了的产品可以提前赎回吗？</p>
			<p><span>A</span>币金所所有产品不支持提前解锁赎回，系统会在锁定期结束后自动把您的数字资产释放到你币金所的账户。</p>
		</div>
		<div style="text-align:center;padding:12px 0;border-top:1px solid #e5e5e5;color:#004097;font-size:12px;" @click="changeOpen(open)">{{open?'收起':'查看更多'}}</div>
	</Card>
</div>
</div>
<mt-popup v-model="popupVisible1" class="pop-top-content" position="top" :visible='true'>
	<div class="pop-top">
		<div class="userinfo" @click="gozichan">
			<p class="title">我的资产（BTC）</p>
			<p class="earn">{{userinfocoinData.value}}</p>
			<p class="suodin">已锁定{{userinfocoinData.lockValue}}</p>
			<span class="iconfont icon-xiangyou"></span>
		</div>
		<cell :data="swipeList"></cell>
	</div>
</mt-popup>
<div class="det_btnbg">
  <button class="det_btn" :class="{ 'det_btn_n': list.status != 2 }" @click="buy(checkbox)">
  {{getText}}
</button>
<!-- <a href="http://wpa.qq.com/msgrd?v=3&uin=123456&site=在线客服&menu=yes">点击这里给我发消息</a>  
<a href='http://wpa.qq.com/msgrd?V=1&Uin=123456&Site=在线咨询&Menu=yes' title='在线即时交谈'>在线即时交谈</a>  
<a href="mqqwpa://im/chat?chat_type=wpa&uin=123456&version=1&src_type=web&web_src=oicqzone.com">咨询客服</a>  //app  
<a href="weixin://dl/business/?ticket=t55f3ecb5a4afee600931a5d334fe77c4#wechat_redirect='http://192.168.1.72:8081/coin/html/share.html'">微信app</a>  -->
</div>
<div class="pay-bg" v-if="flag">
        <div class="pay-tool">
            <div class="pay-tool-title border-bottom">
            <span  @click="backHandle()" class="iconfont icon-zuo"></span><strong>请输入交易密码</strong>
            </div>
            <div class="pay-tool-content">
            <div class="pay-tool-inputs">
                <div class="item" v-for="(i,key) in items" :key="key"><span class="icon_dot" v-if="password[i]"></span></div>
            </div>
            </div>
            <div class="pay-tool-keyboard">
            <ul>
                <li @click="keyUpHandle($event)" v-for="(val,key) in keys" :key="key">
                {{ val }}
                </li>
                <li class="del" @click="delHandle"><span class="icon-del" style="font-size:14px">回退</span></li>
            </ul>
        </div>
     </div>
   </div>
<mt-popup
        v-model="popupVisible">
        <div class="d_fade">
          <div class="df_h">{{list.coinType}} {{list.name}}</div>
        <div class="df_inpu"><input type="text" placeholder="请输入投资额度" v-model="quantity"></div>
        <div class="detpop_btnbg">
          <button @click="close()">取消</button>
          <button @click="dopost(quantity)">提交</button>
          </div>
        </div>
      </mt-popup>
      <!-- <div class="sharebg" v-if="shareflag">
        <div class="sharebox">
          <div class="sharecontent">
            <div class="share_head">分享到</div>
            <div class="sharebtn">
              
              <div><img src="../assets/wechat-button.png" alt="微信"></div>
              <div><img src="../assets/pengyouquan-button.png" alt="朋友圈"></div>
            </div>
          </div>
          <div class="stopshare" @click="closeshare()">取消</div>
        </div>
      </div> -->
  </div>
</template>
<script>
import soshm from "soshm";
import Card from "./main/card";
import util from "../assets/js/util.js";
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
const keys = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, "", 0];
import { Header, Progress, Popup, Toast, MessageBox } from "mint-ui";
import headerBar from "./main/header";
import { productDetail, purchase, userInfo, signature } from "../api/api.js";
import cell from "./main/cell";
import {
  commonShare,
  shareTitle,
  shareUrl,
  shareImg,
  shareDesc
} from "../common/share.js";

export default {
  name: "Detail",
  data() {
    return {
      swipeList: {
        data: [
          {
            title: "系统消息",
            link: "/msg",
            icon: "iconfont icon-xiaoxi1",
            badge: 0,
            color: ""
          },
          {
            title: "已购产品",
            link: "/bought",
            icon: "iconfont icon-chanpin1",
            color: "#004097",
            value: "0"
          },
          {
            title: "身份认证",
            link: "",
            icon: "iconfont icon-shenfenrenzheng",
            color: "#fbb03b",
            value: "已认证"
          },
          {
            title: "邀请赚币",
            link: "/invitation",
            icon: "iconfont icon-share1",
            value: "成功邀请5个好友立即获得1ETH"
          },
          {
            title: "设置",
            link: "/set",
            icon: "iconfont icon-shezhi",
            color: "#919191"
          }
        ]
      },
      msg: "",
      selected: "detail",
      id: "",
      list: "",
      popupVisible: false,
      quantity: "",
      flag: false,
      status: "",
      phone: "",
      items: [0, 1, 2, 3, 4, 5],
      keys: keys(),
      password: [],
      cote: "",
      sharelist: {},
      checkbox: true,
      userstatus: "",
      open: false,
      time: "",
      title: "",
      left: {
        status: true,
        icon: "1"
      },
      right: {
        status: true,
        icon: "iconfont icon-ai221",
        text: "136****49"
      },
      lineVal: 0,
	  popupVisible1: false, //弹出顶部菜单
	  userinfocoinData:{}
    };
  },
  computed: {
    ...mapState(["pageInfo"]),
    //:class="list.status  det_btn"
    getText() {
      let status = {
        2: "立即赚币",
        3: "本期已售罄",
        5: "本期已结束"
      };
      return status[this.list.status];
    }
  },
  methods: {
    gozichan() {
      this.$router.push({ path: "/zichan" });
    },
    goHis() {
      this.$router.push({
        path: "/oldincome",
        query: {
          dayType: this.list.dayType,
          coinType: this.list.coinType,
          type: this.list.type
        }
      });
    },
    rightClick() {
      if (!this.pageInfo.userinfo) {
        this.$router.push({ path: "/login" });
      } else if(this.pageInfo.userinfo && !this.popupVisible1) {
		//   icon-close
		this.popupVisible1 = true;
		this.right.icon = "iconfont icon-close";
      }else{
		  this.popupVisible1 = false;
		this.right.icon = "iconfont icon-ai221";
	  }
    },
    backHandle() {
      this.flag = false;
      var targetDate = "1533225600000"; // 目标日期（活动截止时间）
    },
    changeOpen(ope) {
      this.open = !ope;
    },
    keyUpHandle(e) {
      let text = e.currentTarget.innerText;
      let len = this.password.length;
      if (!text || len >= 6) return;
      this.password.push(text);
      // this.ajaxData();
    },
    delHandle() {
      if (this.password.length <= 0) return false;
      this.password.shift();
    },
    ajaxData() {
      if (this.userstatus == 1) {
        MessageBox.confirm("您还没有认证身份，去认证？").then(action => {
          this.$router.push({ path: "/certification?status=1" });
        });
      } else if (this.userstatus == 3) {
        MessageBox.confirm("您的身份正在认证中，去查看？").then(action => {
          this.$router.push({ path: "/certification?status=3" });
        });
      }
      if (this.status == 1) {
        this.password = [];
        this.flag = false;
        this.popupVisible = false;
        MessageBox.confirm("您还没有交易密码，去设置交易密码？").then(
          action => {
            this.$router.push({ path: "/pay/" + this.mobilephone });
          }
        );
      }
      if (this.status == 2 && this.userstatus == 2 && this.quantity > 0) {
        if (this.password.length >= 6) {
          let para = {
            productId: this.id,
            userId: JSON.parse(sessionStorage.getItem("user")).id,
            token: JSON.parse(sessionStorage.getItem("token")),
            quantity: this.quantity,
            payPwd: parseInt(this.password.join(" ").replace(/\s/g, ""))
          };
          purchase(para)
            .then(res => {
              Toast({
                message: res.msg,
                position: "bottom",
                duration: 5000
              });
              this.flag = false;
              this.password = [];
              this.quantity = "";
              if (res.code == 200) {
                this.popupVisible = false;
              }
            })
            .catch(err => {
              Toast({
                message: "请求超时",
                position: "bottom",
                duration: 5000
              });
            });
        }
      }
      return false;
    },
    getDetail(ev) {
      let para = {
        id: this.id,
        token: sessionStorage.getItem("token")
      };
      this.$ajaxGet("productDetail", para).then(res => {
        this.list = res.data;
        this.time = "";
        let num = 0;
        this.title = res.data.name;
        let timer = setInterval(() => {
          num++;
          // console.log(util.getEndTime(this.list.endTime))
          this.time = util.getEndTime(this.list.endTime);
          if (this.time == "活动已结束") {
            clearInterval(timer);
          }
        }, num == 0 ? 0 : 1000);
        this.lineVal =
          (this.list.totalAmountView - this.list.surplusAmountView) /
          this.list.totalAmountView *
          100;
        this.cote = (
          this.list.totalAmountView - this.list.surplusAmountView
        ).toFixed(2);
      });
    },
    getEndTime() {
      return util.getEndTime(this.list.endTime) || "";
    },
    goshare() {
      soshm.popIn({
        url: "http://www.lalianjob.com/coindist/#/",
        title: "币金所",
        digest: "用币理财，让闲币增加",
        // pic: "../assets/share.png",
        sites: [
          "qq",
          "weixin",
          "weixintimeline"
          // "weibo",
          // "yixin",
          // "tqq",
        ]
      });
      // this.shareflag = true;
      // document.documentElement.style.overflow = "hidden";
      // document.addEventListener(
      //   "touchmove",
      //   function(event) {
      //     event.preventDefault();
      //   },
      //   false
      // );
      var box = document.getElementsByClassName("soshm-pop-sites")[0];
      box.getElementsByClassName("weixin")[0].onclick = function() {
        location.href = "weixin://";
      };
      box.style.background = "#FFF";
      box.style.position = "fixed";
      box.style.bottom = "0";
      // box.style.top="-100%";
      box.style.transform = "none";
      box.style.top = "auto";
      var pa = document.createElement("div");
      pa.style.textAlign = "center";
      pa.style.height = "50px";
      pa.style.lineHeight = "50px";
      pa.style.borderTop = "1px solid #e6e6e6";
      var group = document.getElementsByClassName("soshm-group")[0];
      group.style.padding = "30px 50px";
      var node = document.createTextNode("取消");
      pa.click = function() {
        document.getElementsByClassName("soshm-pop")[0].style.display = "none";
      };
      pa.appendChild(node);
      box.appendChild(pa);
      // this.$router.push({ path: "/share" });
      let para = {
        url: "",
        token: sessionStorage.getItem("token")
          ? JSON.parse(sessionStorage.getItem("token"))
          : ""
      };
      signature(para)
        .then(res => {
          // console.log(res);
          this.sharelist = res;
        })
        .catch(err => {
          Toast({
            message: "请求超时",
            position: "bottom",
            duration: 5000
          });
        });
    },
    dopost(d) {
      if (d <= 0) {
        this.password = [];
        this.flag = false;
        Toast({
          message: "请输入有效的额度",
          position: "bottom",
          duration: 5000
        });
      } else {
        this.flag = true;
      }
    },
    buy(check) {
      this.quantity = "";
      if (this.list.status != 2) {
        return false;
      }
      this.$router.push({
        path: "/buy?id=" + this.list.id
      });
    },
    close() {
      this.popupVisible = false;
    },
    closeshare() {
      // this.shareflag = false;
      document.documentElement.style.overflow = "auto";
      document.addEventListener(
        "touchmove",
        function(e) {
          e.returnValue = true;
        },
        false
      );
    },
    getuser() {
      let para = {
        id: sessionStorage.getItem("user")
          ? JSON.parse(sessionStorage.getItem("user")).id
          : "",
        token: sessionStorage.getItem("token")
          ? JSON.parse(sessionStorage.getItem("token"))
          : ""
      };
      userInfo(para)
        .then(res => {
          this.status = res.data.statusPay;
          this.userstatus = res.data.status;
          if (res.data.status == 1) {
            MessageBox.confirm("您还没有认证身份，去认证？").then(action => {
              this.$router.push({ path: "/certification?status=1" });
            });
          } else if (res.data.status == 3) {
            MessageBox.confirm("您的身份正在认证中，去查看？").then(action => {
              this.$router.push({ path: "/certification?status=3" });
            });
          } else if (res.data.statusPay == 1) {
            this.flag = false;
            this.popupVisible = false;
            this.phone = res.data.mobilephone;
            MessageBox.confirm("您还没有交易密码，去设置交易密码？").then(
              action => {
                this.$router.push({ path: "/pay/" + res.data.mobilephone });
              }
            );
          } else {
            this.popupVisible = true;
          }
        })
        .catch(err => {
          Toast({
            message: "请求超时",
            position: "bottom",
            duration: 5000
          });
        });
	},
	initUserinfo() {
      if (util.getLocalStorage("userinfo")) {
        this.$ajaxGet("userInfo", {
          id: this.pageInfo.userinfo.id,
          token: util.getLocalStorage("token")
        }).then(res => {
		  this.pageInfo.userinfo = res.data;
		  res.data.coinData.forEach((item,index) => {
			  if(item.coinType == "BTC"){
				  this.userinfocoinData = item;
				  this.userinfocoinData.value = this.userinfocoinData.value.toFixed(4);
				  this.userinfocoinData.lockValue = this.userinfocoinData.lockValue.toFixed(4)
			  }
		  })
          util.setLocalStorage("userinfo",JSON.stringify(this.pageInfo.userinfo));
        });
      }
    },
  },
  components: {
    Card,
    headerBar,
    cell
  },
  mounted() {
    document.body.scrollTop = 0;
    this.id = this.$route.query.id;
	this.getDetail();
	this.initUserinfo();
  },
  created() {
    if (!this.pageInfo.userinfo) {
      this.right.text = "注册/登录";
      this.right.icon = "";
    } else {
      this.right.text = util.getPhone(this.pageInfo.userinfo.mobilephone || "13698006449");
      this.right.icon = "iconfont icon-ai221";
	}
	this.swipeList.data[2].link = `${'/certification?status='+this.pageInfo.userinfo.status}`;
	let status = {
		1:"未认证",
		2:"已认证",
		3:"审核中"
	}
	this.swipeList.data[0].badge = this.pageInfo.userinfo.messageCount;
	this.swipeList.data[1].value = this.pageInfo.userinfo.productCount;
	
	this.swipeList.data[2].value = status[this.pageInfo.userinfo.status];
  },
  watch: {
    popupVisible1(now){
      if(!now && this.pageInfo.userinfo){
		  this.right.icon = "iconfont icon-ai221";
	  }
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
@import url("../../static/css/detail.css");
@import url("../../static/css/pay.css");
.soshm-pop-sites {
  background: #fff !important;
}
.history .mint-cell .mint-cell-wrapper .mint-cell-title .mint-cell-text {
  color: #888888 !important;
}
.det_btn_n {
  background: #bbbec7 !important;
}
</style>
